<template>
    <div
        class="BillingResendCommon topStyley"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <el-card class="box-card">
            <div slot="headerss" class="clearfix text_fl">
                <span>补寄账单</span>
                <el-button class="btn_close" type="text" @click="handleClose">关闭</el-button>
            </div>
            <div>
                <div>
                    <el-form
                        ref="formData"
                        :model="formData"
                        :rules="rules"
                        label-width="150px"
                        style="margin-top:10px;"
                    >
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <el-form-item label="账户类别:" class="text_fl">
                                    <span class="el-form-item-span">{{formData.CATEGORY}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item label="主卡卡号:" class="text_fl">
                                    <span class="el-form-item-span">{{formData.CARDNBR}}</span>
                                </el-form-item>
                            </el-col>

                            <el-col :span="11" :offset="1">
                                <el-form-item label="当前账单寄送方式:" class="text_fl" prop="STMTTYPE">
                                    <span class="el-form-item-span">{{ formData.STMCODE_filter }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11" v-if="formData.STMTTYPE == '1'">
                                <el-form-item label="EMAIL:" class="text_fl">
                                    <span class="el-form-item-span">{{formData.EMAIL}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11" v-if="formData.STMTTYPE == '0'">
                                <el-form-item label="账单地址:" class="text_fl">
                                    <span
                                        class="el-form-item-span"
                                    >{{formData.SADDTYPEVlaue |formaddtype(stmtypeList) }}</span>
                                </el-form-item>
                            </el-col>

                            <el-col :span="22" :offset="1">
                                <el-form-item label="补寄时间:" class="text_fl" prop="BILLTERM">
                                    <el-checkbox-group
                                        name="last24MthsList"
                                        v-model="formData.BILLTERM"
                                        :min="0"
                                    >
                                        <el-checkbox
                                            v-for="item in last24MthsList"
                                            :label="item"
                                            :key="item"
                                        ></el-checkbox>
                                    </el-checkbox-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="22" :offset="1">
                                <el-form-item label="快速补寄:" class="text_fl">
                                    <el-radio-group v-model="quickMonths" @change="radioChange">
                                        <el-radio :label="3">近3个月</el-radio>
                                        <el-radio :label="6">近6个月</el-radio>
                                        <el-radio :label="12">近12个月</el-radio>
                                        <el-radio :label="24">近24个月</el-radio>
                                        <el-radio :label="-1">全部清空</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- 话术 -->
                        <div class="hstable_wrap" v-if="speechList.length!=0">
                            <el-table
                                :data="speechList"
                                border
                                stripe
                                header-row-class-name="headerRow"
                                ref="showListTable"
                                class="heard-bg business_table hstable"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                                <el-table-column label="业务话术">
                                    <template slot-scope="scope">{{scope.row.content}}</template>
                                </el-table-column>
                            </el-table>
                        </div>

                        <div class="text_center">
                            <el-button
                                type="primary"
                                size="small"
                                @click="handleclickForm"
                                icon="el-icon-circle-check"
                                v-preventReClick
                            >确定</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                @click="updatehistory"
                                v-show="isShowView"
                            >修改记录查询</el-button>
                        </div>
                    </el-form>
                    <div
                        style="margin-top:10px;margin-bottom:30px;"
                        align="center"
                        v-show="isShowView"
                    >
                        <el-table
                            :data="tryData"
                            border
                            stripe
                            class="heard-bg business_table"
                            style="width: 80%;"
                            size="small"
                        >
                            <el-table-column label="操作结果">
                                <el-table-column prop="BILLTERM" label="补寄时间"></el-table-column>

                                <el-table-column prop="RSPMSG" label="交易结果"></el-table-column>

                                <el-table-column prop="ERRMSG" label="结果描述"></el-table-column>
                            </el-table-column>
                        </el-table>
                    </div>

                    <el-dialog
                        v-drag
                        title="补印账单申请"
                        :visible.sync="centerDialogVisible"
                        width="500px"
                        :append-to-body="true"
                        top="30vh"
                        :close-on-click-modal="false"
                        center
                    >
                        <p>
                            当前账单寄送方式:
                            <span>{{this.formData.STMCODE_filter}}</span>
                        </p>
                        <p>
                            补寄时间:
                            <span>{{this.billterms}}</span>
                        </p>

                        <p class="text_center padding_top15" v-if="this.iffree=='0'">
                            <span style="color:#3a8ee6; ">是否确认办理补寄账单？</span>
                        </p>
                        <p class="text_center padding_top15" v-if="this.iffree=='1'">
                            <span style="color:#3a8ee6; ">当前补寄纸质账单超过近三期，可能产生费用，是否确认办理？</span>
                        </p>
                        <span slot="footer" class="dialog-footer">
                            <el-button size="small" @click="centerDialogVisible = false">取 消</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                @click="getReprintBill"
                                icon="el-icon-circle-check"
                                v-preventReClick
                            >确定</el-button>
                        </span>
                    </el-dialog>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import moment from 'moment';
import { mapState, mapGetters } from 'vuex';
import {
    closePage, getInstalmentList, getDictSelectList, getDictMappingValue,
} from '@/utils/Common';
import { isEmptyObject } from '@/utils/Object';
import { get_4xxx, get_3xxx } from '@/apis/getAPIClass';
import { BILLINGMETHOD } from '@/utils/Contants';

export default {
    name: 'BillingResendCommon',
    data() {
        return {
            formData: {
                CATEGORY: '',
                CARDNBR: '',
                EMAIL: '', // E_mail
                ADD1: '', // 账户账单地址
                BILLTERM: [], // 账单年月 yymm
                STMTTYPE: '1', // 账单递送方式，表单提交4003申请用， 0-邮寄账单、1-电子账单
                MLTYPE: '', // 账单递送方式   MLTYPE
                ADDTYPE: '', // 账单地址类型
                SADDTYPEVlaue: '', // 账单地址的值
                FEEFLAG: '0', // 补印账单是否收费 0：不收费；1：收费
                STMCODE: '', // 当前账单递送方式（3014获取），页面显示用，EM-电子账单、LT-纸质账单
                STMCODE_filter: '', // 页面显示（电子账单、纸质账单）
            },
            rules: {
                BILLTERM: [{ required: true, message: '请选择打印的账单日期！' }],
                STMTTYPE: [{ required: true, message: '补印账单递送方式不能为空！' }],
                // EMAIL: [{ required: true, message: 'email为空不能发送电子邮件申请!' }],
            },
            creditCard_3014: {},
            reprintBill_4003: {},
            centerDialogVisible: false,
            last24MthsList: [], // 近12个月账期
            option: 'L', //币种选项：L第一币种，I第二币种
            quickMonths: '', //快速补寄（近n月）
            speechCraftList: [], //话术列表
            stmtypeList: [],//账单地址类型
            iffree: '0',//补寄是否收费,0-不收费，1-收费

            isShowView: false,
            resultData: {},//4003交易结果
            tryData: [
                {
                    BILLTERM: '',
                    RSPMSG: '',
                    ERRMSG: ''
                },
            ],
            speechList: [],//话术列表
            selectedList: [],
            pageLoading: true,
            billterms: '',
        };
    },
    computed: {
        ...mapGetters([
            'defaultParams',
            'cardInfo_3004',
            'pinFlag',
            'isCurrentMenuInfo',
        ]),
        isreprintBill_4003() {
            return isEmptyObject(this.reprintBill_4003);
        },
    },
    filters: {
        isStmtType: (value) => {
            value += '';
            if (value.trim() === '3') {
                return '无任何方式账单';
            } if (value.trim() === '0') {
                return '纸质账单';
            } if (value.trim() === '1') {
                return '电子账单';
            } if (value.trim() === '2') {
                return '纸质+电子';
            }
        },
        formaddtype(val, stmtypeList) {

            const txt = val.trim();
            let text = '';
            stmtypeList.forEach((item) => {
                if (item.code + '' === txt + '') {
                    text = item.label;
                }
            });
            return text;
        },

    },
    mounted() {
        this.formData.CARDNBR = this.cardInfo_3004.CARDNO;
        this.getDictValue();
        this.getLast12MthsAcctPeriod(); //加载最近12个月的账期
    },
    methods: {
        async getDictValue() {
            await this.getspeechList();
            // 账户类型
            console.log(this.cardInfo_3004.CATEGORY, 'CATEGORY');

            this.stmtypeList = await getDictSelectList('STSMAIL', this);//账单地址类型

            this.formData.CATEGORY = await getDictMappingValue('CATE', this.cardInfo_3004.CATEGORY, this);
            await this.getCreditCardInfo();
            // 账户账单代码 STMCODE LT-纸质 EM-电子
            console.log(this.creditCard_3014.STMCODE, 'STMCODE');
            // this.formData.STMCODE_filter = await getDictMappingValue('STMCD', this.creditCard_3014.STMCODE, this);
            // if ((`${this.formData.STMCODE_filter}`).trim() === '') {
            //     this.formData.STMCODE_filter = '无任何账单寄送方式';
            // };
            if (this.creditCard_3014.STMCODE == 'LT') {
                this.formData.STMTTYPE = '0';
                this.formData.STMCODE_filter = '纸质账单';
                this.formData.FEEFLAG = '1';
            } else if (this.creditCard_3014.STMCODE == 'EM') { //支持纸质和电子，默认电子
                this.formData.STMTTYPE = '1';
                this.formData.STMCODE_filter = '电子账单';
                this.formData.FEEFLAG = '0';
            } else {
                this.formData.STMTTYPE = '';
                this.formData.STMCODE_filter = '无';
                this.formData.FEEFLAG = '0';
            }

            this.formData.CARDNBR = this.creditCard_3014.CARDNBR;
            this.formData.EMAIL = this.creditCard_3014.EMAIL;
            // this.formData.ADD1 = this.creditCard_3014.ADD1;
            this.formData.ADDTYPE = this.creditCard_3014.ADDTYPE;

            this.formData.SADDTYPEVlaue = this.creditCard_3014.ADDTYPE;
            // this.setSelectValue();


        },

        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            var checkParam = {
                'id': this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    } else {
                        const ErrorMessage = `错误码：${res.data.status} ` + `错误信息：${res.data.msg}`;
                        this.$alert(ErrorMessage, '请求异常:', {
                            customClass: 'error', type: 'error',
                        });
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        filterDateYYYYMMDD(value) {
            value = (`${value}`).trim();
            if (value === '00000000') return value;
            if (value) {
                return moment(value, 'YYYYMMDD').format('YYYY-MM');
            }
            return '';
        },
        handleclickForm() {

            this.$refs.formData.validate((valid) => {
                if (valid) {
                    this.iffree = '0';
                    if (this.selectedList.length != this.speechList.length) {
                        this.$alert('话术尚未全部勾选！', '提示', {
                            customClass: 'warning', type: 'warning',
                        });
                        return;
                    }
                    this.billterms = '';
                    //this.formData.BILLTERM.forEach();
                    let newaraay = this.formData.BILLTERM.sort(function (a, b) {
                        return b - a;
                    });
                    for (let i in newaraay) {
                        this.billterms = this.billterms + newaraay[i] + '、';
                    }
                    this.billterms = this.billterms.substring(0, this.billterms.length - 1);
                    let oct = 0;
                    for (let i = 0; i < this.formData.BILLTERM.length; i++) {
                        console.log("this.formData.BILLTERM[i]", this.formData.BILLTERM[i]);
                        if (this.formData.BILLTERM[i] + '' != this.last24MthsList[0] + '' && this.formData.BILLTERM[i] + '' != this.last24MthsList[1] + ''
                            && this.formData.BILLTERM[i] + '' != this.last24MthsList[2] + '') {

                            oct++;
                            console.log("oct", oct);
                        }
                    }

                    if (oct > 0 && this.formData.STMTTYPE === '0') {//纸质账单并且补寄时间有超过近三期的，提醒收费
                        this.iffree = '1';
                    }
                    console.log("this.iffree", this.iffree, "this.formData.STMTTYPE", this.formData.STMTTYPE);
                    this.centerDialogVisible = true;
                }
            });

        },
        // 补印账单是否收费 默认收费 电子账单打印小于一年时不收费（大于一年 =》无法补印24月以上的电子账单！）
        // 电子账单 需要邮箱 必填（email为空，不能发送电子邮件申请!）
        //  纸质账单 不收费 无法补寄12个月以上的纸质账单
        // submitForm(){
        // let months = this.formData.BILLTERM;
        // 6409 银行做下面的校验
        // if(this.formData.STMTTYPE ==='1' && months<=24){
        //     this.formData.FEEFLAG = '0';//不收费
        // }else{
        //     this.$alert('无法补印24月以上的电子账单！','提示')
        //     return false;
        // }
        // if(this.formData.STMTTYPE ==='0' && months<=12){
        //     this.formData.FEEFLAG = '0';//不收费
        // }else{
        //     this.$alert('无法补寄12个月以上的纸质账单!','提示'); return false;
        // }

        // },
        //

        // 3014信用卡服务方式综合查询 查字典 billsnd
        async getCreditCardInfo() {
            const defaultParamInfo = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParamInfo.body.appHead.tranCode = '3014';// 修改交易号
            defaultParamInfo.body.appBody = {
                PINFLAG: this.pinFlag,
                PIN: '',
                CARDNBR: this.formData.CARDNBR,// 卡号
            };
            await this.$post.common.transPort(defaultParamInfo).then((res) => {
                this.pageLoading = false;
                console.log(res);
                if (res.status === 200) { // 请求成功
                    const CreditCard = JSON.parse(res.data.jsonRes);
                    console.log(CreditCard, '3014信用卡服务');
                    if (CreditCard.sysHead.rspCd == '000000') { // 交易成功
                        this.creditCard_3014 = CreditCard.body.appBody;
                        // this.isShowSuccess=true;
                    } else {
                        const ErrorMessage = `错误码：${CreditCard.sysHead.rspCd} ` + `错误信息：${CreditCard.sysHead.rspMsg}`;
                        // this.$alert(ErrorMessage, CreditCard.sysHead.busiName, {
                        //     customClass: 'error', type: 'error',
                        // });
                    }
                }
            });
        },

        // 4003补印账单或密码函
        async getReprintBill() {
            this.tryData = [];
            this.centerDialogVisible = false;
            var selectedmths = this.formData.BILLTERM; //账单选中年月数组
            console.info("============getReprintBill-selectedmths：", selectedmths);
            for (let index = 0; index < selectedmths.length; index++) {
                this.resultData = {};
                let result = { BILLTERM: '', RSPMSG: '', ERRMSG: '' };
                const element = selectedmths[index] + "";
                var billDate = element.substr(2, 4);
                await this.transPort4003(billDate);

                console.log("this.resultData2", this.resultData);
                if (this.resultData.sysHead.rspCd == '000000') {
                    result = { BILLTERM: element, RSPMSG: '补寄成功', ERRMSG: '' };
                } else {
                    result = { BILLTERM: element, RSPMSG: '补寄失败', ERRMSG: this.resultData.sysHead.rspMsg };
                }


                this.tryData.push(result);

            }
            this.isShowView = true;
            console.log("this.tryData", this.tryData);


            // const successMessage = `补印账单申请成功！`;
            // const ts = `提示`;
            // this.$alert(successMessage, ts, {
            //     customClass: 'success', type: 'success',
            // });
        },

        async transPort4003(billDate) {
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '4003';// 修改交易号
            defaultParams.body.appBody = {
                OPTION: '1',
                PINFLAG: this.pinFlag,
                PIN: '',
                CARDNBR: this.formData.CARDNBR,
                BILLTERM: billDate, //账单年月
                FEEFLAG: this.formData.FEEFLAG,
                STMTTYPE: this.formData.STMTTYPE,
                MLTYPE: '', // 账单快递方式  只有在“补印账单类型”为“邮寄账单”或“邮寄与电子邮件两者”时填写。其值为银行在CODES(ZDKDT)中的定义。都给空
                KFEFLAG: '', // 账单快递费  只有在“补印账单类型”为“邮寄账单”或“邮寄与电子邮件两者”时填写。空或0：无 1：同城 2：外地 3：海外  都给空
            };
            console.log('==========transPort4003-billDate：' + billDate);
            await this.$post.common.transPort(defaultParams).then((res) => {
                console.log('==========transPort4003-res：', res);
                if (res.status === 200) { // 请求成功
                    const ReprintBill = JSON.parse(res.data.jsonRes);
                    this.resultData = ReprintBill;
                    console.log("this.resultData1", this.resultData);
                    // if (ReprintBill.sysHead.rspCd == '000000') { // 交易成功
                    //     // this.reprintBill_4003 = ReprintBill.body.appBody;
                    //     // const successMessage = `卡号：${this.formData.CARDNBR} 补印账单申请成功！`;
                    //     // const ts = `${ReprintBill.sysHead.busiName}提示`;
                    //     // this.$alert(successMessage, ts, {
                    //     //     customClass: 'success', type: 'success',
                    //     // });
                    // } else {
                    //     const ErrorMessage = `错误码：${ReprintBill.sysHead.rspCd} ` + `错误信息：${ReprintBill.sysHead.rspMsg}`;
                    //     this.$alert(ErrorMessage, ReprintBill.sysHead.busiName, {
                    //         customClass: 'error', type: 'error',
                    //     });
                    // }
                    //return ReprintBill;
                }
                //this.centerDialogVisible = false;// 交易完成关闭弹框
            });
        },

        addressEdit() {
            this.$router.push({ path: '/customerInfomationChange/addressEdit' });
        },
        // 关闭页面
        handleClose() {
            closePage(this.$route, this, 1);
        },

        //获取近12个月有账单的账期日期
        async getLast12MthsAcctPeriod() {
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '3054';// 交易号-卡片信用历史查询
            defaultParams.body.appBody.CARDNBR = this.cardInfo_3004.CARDNO || '';//卡号
            defaultParams.body.appBody.OPTION = this.option;//币种选项：L第一币种，I第二币种
            defaultParams.body.appBody.PINFLAG = this.pinFlag;// 验密

            var result_3054 = {};

            var queryResListAll = [];
            // 循环遍历4次查询24个月内账期日期,QUERY:::0:6个月内，1:6-12月，2:13-18月，3:19-24月
            for (let index = 0; index <= 3; index++) {
                console.info('============循环遍历查询账期日期，index=：' + index);
                defaultParams.body.appBody.QUERY = index;// 验密

                var queryResListTemp = [];
                await this.$post.common.transPort(defaultParams).then((res) => {
                    console.info('============循环遍历res：', res);
                    if (res.status === 200) { // 请求成功
                        const cardserver = JSON.parse(res.data.jsonRes);
                        if (cardserver.sysHead.rspCd == '000000') { // 交易成功
                            result_3054 = cardserver;
                            queryResListTemp = result_3054.body.appBody.dataList || [];
                            console.info('============循环遍历查询结果，queryResListTemp：', queryResListTemp);
                            // 合并查询
                            queryResListAll = queryResListAll.concat(queryResListTemp);
                        }
                    }
                });

            }
            console.info('============循环遍历结束，合并结果queryResListAll：', queryResListAll);

            // 查询结果遍历取日期值封装入多选框绑定变量
            for (let index = 0; index < queryResListAll.length; index++) {
                const temp = queryResListAll[index];
                if (temp.CLOSEDAY != '00000000') {
                    var closeDayStr = temp.CLOSEDAY + '';
                    this.last24MthsList.push(closeDayStr.substr(0, 6));
                }
            }

            console.info('============last24MthsList：', this.last24MthsList);

        },

        radioChange(val) {
            if (val == -1) {
                this.formData.BILLTERM = [];
                return;
            }
            this.formData.BILLTERM = [];
            console.info('*********快速补寄，val=' + val);
            var pushs = this.last24MthsList.slice(0, val);
            for (let index = 0; index < pushs.length; index++) {
                const element = pushs[index];
                if (this.formData.BILLTERM.indexOf(element) === -1) { //控制不重复添加
                    this.formData.BILLTERM.push(element); //账单选中年月数组
                }
            }
            console.info('====================================快速补寄后的选中数组BILLTERM', this.formData.BILLTERM);
        },

        updatehistory() {
            this.$router.push({ path: '/businessSystem/accountCardDetaileQuery' });
        },
    },
};
</script>

<style lang='scss' >
.BillingResendCommon {
    .el-card__header {
        padding: 8px !important;
    }
    /* 
    .el-form-item-input input,
    .el-input input {
        width: 250px;
        min-width: 200px;
        height: 35px;
        line-height: 35px;
    } */

    .text_center {
        text-align: center;
    }
    /* .el-select {
        input {
            max-width: 300px;
            min-width: 150px;
            height: 35px;
            line-height: 35px;
        }
    } */
    .el-card.is-always-shadow {
        -webkit-box-shadow: none;
        box-shadow: none;
    }
    .quickMonthss .el-form-item__content {
        text-align: left;
        line-height: 36px;
    }
    .BILLTERM_inline .el-form-item__content {
        line-height: 26px;
    }
    .el-card {
        border: none;
    }
}
</style>
